<?php

namespace app\common\model;

use app\common\model\marketing\MarketingCoupons;
use fast\Date;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use think\Exception;
use fast\Time;
use app\common\model\Order as OrderModel;

class Goods extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';
    //表名
    protected $name = 'goods';
    //expired
    const DEADLINETYPE_0 = 0; //当日有效
    const DEADLINETYPE_1 = 1; //有效期当日及前后
    const DEADLINETYPE_2 = 2; //自定义有效时间

    const EXPIRED_0 = 0;    //不处理
    const EXPIRED_1 = 1;    // 自动完结
    const EXPIRED_2 = 2;    //自动验证
    const EXPIRED_3 = 3;    //自动退款
    protected static $_goods = NULL;

    // 追加属性
    protected $append = [
        // 'assembling_place_text',
    ];

    /**
     * @return |null
     * 获取单个商品数据
     */
    public function goods()
    {
        return self::$_goods;
    }

    public function setGoods($value)
    {
        self::$_goods = $value;
    }


    /**
     * [getGoodsIdList 获取景区下的所有商品id]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-18
     * @param    [type]      $store_id  [description]
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    // public function getGoodsIdList($shop_id,$scenic_id)
    // {   
    //     return self::_getGoodsId($shop_id,$scenic_id);
    // }

    /**
     * [del 删除景区，同时删除商品]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    public function del($scenic_id)
    {
        $list = $this->where('scenic_id', 'in', $scenic_id)->select();
        $count = 0;
        foreach ($list as $k => $v) {
            $count += $v->delete();
        }
        if ($count) {
            return true;
        } else {
            return false;
        }
    }


    /***
     * @param $value
     * @return mixed
     * 提前购买状态
     */
    public function getBeforeStatusAttr($value)
    {
        $status = [0 => '即买即用', 1 => '可订明日', 2 => '需提前购买'];
        return $status[$value];
    }

    /***
     * @param $value
     * @return mixed
     * 退款规则状态
     */
    public function getRefundStatusAttr($value)
    {
        $status = [0 => '不可退款', 1 => '随时退款', 2 => '有条件退款'];
        return $status[$value];
    }

    //星期列表
    public function getWeekList()
    {
        return [1 => '周一', 2 => '周二', 3 => '周三', 4 => '周四', 5 => '周五', 6 => '周六', 0 => '周日'];
    }

    //获取有效期可用时间数组
    public function getValidPeriodWeekAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['valid_period_week']) ? $data['valid_period_week'] : '');
        $valueArr = explode(',', $value);
        return $valueArr;
    }

    //获取有效期可用时间数组
    public function getValidPeriodWeekTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['valid_period_week']) ? $data['valid_period_week'] : '');
        if (!is_array($value)) {
            $valueArr = explode(',', $value);
        } else {
            $valueArr = $value;
        }
        $list = $this->getWeekList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    /***
     * @return \think\model\relation\BelongsTo
     * 关联景区
     */
    public function scenic()
    {
        return $this->belongsTo('Scenic', 'scenic_id')->field('id,scenic_name,scenic_images');
    }

    /**
     * @param $play_time 游玩日期
     * @param $goods_id  商品Id
     * @return bool
     * 验票结束结束购买
     * check_in_time_end
     */
    public static function checkInTimeEnd($play_time, $goods_id)
    {
        $end_time = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
        $model = new static;
        if ($play_time >= $end_time) {
            //游玩时间提前购买
            return true;
        }
        $goods = self::get(['id' => $goods_id]);
        $check_time = $model->join_time(time(), $goods['check_end_time']);//当前验票时间
        if ($goods['deadlineType'] == self::DEADLINETYPE_2) {
            return true;
        }
        return $model->timeSize($check_time);
    }

    /**
     * @param array $goods
     * @return int|mixed
     * 计算上架倒计时秒
     */
    protected function setCountdown($goods = [])
    {
        $countdown = 0;
        if (!$goods) {
            return $countdown;
        }

        if ($goods['goods_status']) {
            if ($goods['unShelve'] == 1 && \time() >= $goods['unShelveStartTime']) {

                $countdown = $goods['unShelveEndTime'] - \time();
                $countdown = $countdown > 0 ? $countdown : 0;
            }

        } else {
            if ($goods['putaway'] == 3 && \time() >= $goods['putawayStartTimeing']) {

                $countdown = $goods['putawayEndTimeing'] - \time();
                $countdown = $countdown > 0 ? $countdown : 0;
            }
        }

        return $countdown;
    }

    /**
     * [_getGoodsId 获取商品id]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-18
     * @param    [type]      $user_id  [description]
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    private static function _getGoodsId($shop_id, $scenic_id)
    {


        $user = Db::name('user')->field('store_id')->find($shop_id);
        if ($scenic_id) {
            $map['g.scenic_id'] = ['in', $scenic_id];
        } else {
            $map = [];
        }
        $where = ['g.store_id' => $user['store_id'], 'g.goods_status' => 1, 'd.unified' => ['neq', 'not null']];
        if ($shop_id == 2) {
            $where['platform_distributors'] = 2;
        }
        $goodsIds = Db::name('goods')
            ->alias('g')
            ->join('distribution_allocation d', 'd.goods_id = g.id')
            ->where($map)
            ->where($where)
            ->column('goods_id');
        foreach ($goodsIds as $key => $value) {
            $allocation = Db::name('distribution_allocation')->field('unified')->where('goods_id', $value)->find();
            if ($allocation['unified'] == 1) {
                $distributor = Db::name('distributor')->field('id')->where(['user_id' => $shop_id])->find();
                $distributor_goods = Db::name('distributor_goods')
                    ->where(['goods_id' => $value, 'user_id' => $distributor['id'], 'status' => 1])->find();
                if (!$distributor_goods) {
                    unset($goodsIds[$key]);
                }
            }
        }
        return $goodsIds;
    }


    /**
     * [getHotGoods 景区下热门推荐产品]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-23
     * @param    [type]      $shop_id   [description]
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    public static function getHotGoods($goods_ids)
    {
        $goods_id = $goods_ids;
        $model = new static;
        $where = [
            'id' => ['in', $goods_id],
            'goods_status' => 1
        ];
        $list = self::where($where)->limit(3)->order('total_sales', 'desc')->select();
        if ($list) {
            foreach ($list as $key => $goods) {
                $where = ['goods_id' => $goods['id'], 'sales_status' => 1];
                $data[$key]['minPrice'] = Sales::where($where)->min('salePrice'); //该商品最低销售价格
                $data[$key]['retailPrice'] = Sales::retail_price($where); //该商品的门市价格
                $data[$key]['total_sales'] = $goods['total_sales'];
                $data[$key]['goods_name'] = $goods['goods_name'];
                $data[$key]['goods_id'] = $goods['id'];
                $data[$key]['button_text'] = $goods['button_text'];
                self::$_goods = $goods;
                $data[$key]['before'] = $model->getBeforeText();
                $data[$key]['tag'] = $model->tag($goods['id'], true);
                $data[$key]['coupons'] = MarketingCoupons::getUsersProductIdsReceiveCoupons($goods['scenic_id'], $goods['id']);

            }
            //热门推荐少于3个，返回空
            if (count($data) < 3) {
                return [];
            }
        } else {
            $data = [];
        }
        return $data;
    }


    /**
     * [getGoods 获取商品分类和分类下的商品]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @param    [type]      $shop_id        [description]
     * @param    [type]      $scenic_id      [description]
     * @param    [type]      $category_id    [description]
     * @param    [type]      $is_distributor [description]
     * @return   [type]                      [description]
     */
    public static function getGoods($shop_id, $scenic_id, $category_id, $is_distributor, $user_id = 0)
    {
        $goods_id = self::_getGoodsId($shop_id, $scenic_id);
        $model = new static;
        $list = GoodsType::where(['category_id' => $category_id, 'status' => 1])->field('id,type_name,depict,category_id')->select();
        $all = ['id' => 0, 'type_name' => '全部', 'depict' => '全部'];
        array_unshift($list, $all);
        $list = collection($list)->toArray();
        $field = [
            'id',
            'goods_name',
            'goods_type_id',
            'total_sales',
            'before',
            'beforeHour',
            'beforeMinute',
            'beforeDay',
            'beforeTime',
            'refundRules',
            'is_virtual_sales',
            'virtual_sales',
            'is_custom',
            'tags',
            'putaway',
            'goods_status',
            'deadlineType',
            'valid_period_start',
            'unShelve',
            'year_card',
            'subtract',
            'time_is_show',
            'entrance_time',
            'entrance_time_notes'
        ];
        $goods_list = self::where(['id' => ['in', $goods_id]])->field($field)->order('weigh desc')->select();
        $goods_list = collection($goods_list)->toArray();
        foreach ($goods_list as &$goods) {
            self::$_goods = $goods;
            $where = ['goods_id' => $goods['id'], 'sales_status' => 1];
            $goods['minPrice'] = Sales::where($where)->min('salePrice'); //该商品最低销售价格
            $goods['retailPrice'] = Sales::retail_price($where);        //该商品的门市价格
            $goods['before'] = $model->getBeforeText();
            $goods['tag'] = $model->tag($goods['id'], true);
            $goods['countdown'] = $model->setCountdown($goods);
            $goods['coupons'] = MarketingCoupons::getUsersProductIdsReceiveCoupons($scenic_id, $goods['id']);
            if ($is_distributor) {
                $allocation = Db::name('distribution_allocation')->where(['goods_id' => $goods['id'], 'unified' => 2])->find();
                if ($allocation) {
                    $distributor = Db::name('distributor')->field('level')->where(['user_id' => $shop_id])->find();
                    switch ($distributor['level']) {
                        case '1':
                            $share_price = 'one_price';
                            break;
                        case '2':
                            $share_price = 'two_price';
                            break;
                        case '3':
                            $share_price = 'three_price';
                            break;
                    }
                    $goods['share_price'] = $allocation[$share_price];
                } else {
                    $distributor = Db::name('distributor')->field('id')->where(['user_id' => $shop_id])->find();
                    $distributor_goods = Db::name('distributor_goods')
                        ->field('market_price')
                        ->where(['goods_id' => $goods['id'], 'user_id' => $distributor['id']])
                        ->find();
                    $goods['share_price'] = $distributor_goods['market_price'];
                }
            } else {
                if ($goods['subtract']) {
                    $allocation = Db::name('distribution_allocation')
                        ->field('subtract,subtract_money,num_restriction,total_restriction,goods_id')
                        ->where(['goods_id' => $goods['id']])->find();
                    $goods['subtract_money'] = $allocation['subtract_money'];
                    $goods['num_restriction'] = $allocation['num_restriction'];
                    $goods['total_restriction'] = $allocation['total_restriction'];
                    $goods['discounts_number'] = $allocation['num_restriction'];
                    $orderModel = new OrderModel();
                    if ($user_id && $allocation) {
                        $userTicketNum = $orderModel->ticketNumNew($user_id, $allocation['goods_id']);
                        if ($allocation['num_restriction'] <= $userTicketNum) {
                            $goods['discounts_number'] = 0;
                        }
                    }
                    //没有限购张数限制
                    if ($goods['num_restriction'] == 0) {
                        $goods['discounts_number'] = -1;
                    }
                    //有总票数限制
                    $totalTicketNum = $orderModel->ticketNumNew(0, $allocation['goods_id']);
                    if ($totalTicketNum >= $goods['total_restriction']) {
                        $goods['discounts_number'] = 0;
                    }
                }
            }


        }
        foreach ($list as $key => &$value) {
            if ($key == 0) {
                $value['goods_list'] = $goods_list;
            } else {
                $goods_list2 = [];
                foreach ($goods_list as $value2) {
                    if ($value2['goods_type_id'] == $value['id']) {
                        $goods_list2[] = $value2;
                    }
                }
                if ($goods_list2) {
                    $value['goods_list'] = $goods_list2;
                    unset($goods_list2);
                }

            }
        }

        return ['list' => $list, 'goods_ids' => $goods_id];
    }


    /**
     * [goodsInfo 商品详情]
     * @Author   ZhouYunpeng
     * @DateTime 2020-03-31
     * @param goods_id 商品id
     */
    public static function goodsInfo($goods_id)
    {
        $goods = self::withTrashed()->where('id', $goods_id)->find();

        self::$_goods = $goods;
        $model = new static;

        $data['entrance'][] = ['title' => '产品说明:', 'value' => $goods['for_people']];
        $data['entrance'][] = [
            'title' => $model->getBeforeDay() . ':',
            'value' => $model->getBeforeText()
        ];
        //有效期
        if ($goods['deadlineType'] == 2) {
            $data['entrance'][] = ['title' => '有效期：', 'value' => $model->getDeadlineTypeText()];
        }

        if ($goods['category_id'] == 1) {
            $title = $goods['parkWays'] == 1 ? '换票入园' : '无需换票';
            $data['entrance'][] = [
                'title' => $title . ':',
                'value' => $model->getParkWaysText()
            ];
            $data['use_instruction'][] = [
                'title' => $goods['parkWays'] ? '换票时间:' : '入园时间:',
                'value' => date('H:i', $goods['check_start_time']) . '—' . date('H:i', $goods['check_end_time']) . ($goods['check_time_notes'] ? ' ' . $goods['check_time_notes'] : ''),
            ];
        }

        if ($goods['parkWays']) {
            $data['entrance'][] = ['title' => '换票地址:', 'value' => $goods['parkCheck']];
        }
        $title2 = $goods['category_id'] == 2 ? '乘车地点' : '入园地址';
        $data['use_instruction'][] = ['title' => $title2, 'value' => $goods['parkDetails']];

        $data['explain'][] = ['title' => '费用包含:', 'value' => $goods['feesInclude']];
        $data['explain'][] = ['title' => '费用不含:', 'value' => $goods['feesNotInclude']];
        $data['explain'][] = ['title' => '发票说明:', 'value' => $goods['invoiceExplain']];
        $data['explain'][] = ['title' => '其他说明:', 'value' => $goods['other']];

        //退、改规则
        $data['refund'] = $model->getRefundRulesText();
        $data['goods_id'] = $goods['id'];
        $data['goods_name'] = $goods['goods_name'];
        $data['buy_times'] = $goods['buy_times'];
        $data['buy_times_num'] = $goods['buy_times_num'];
        $data['min_number'] = $goods['minnum'];
        $data['highest_number'] = $goods['maximum'];

        if (!$goods['buy_times']) {
            //不限制购买次数
            $data['buy_times_num'] = 0;
            $data['min_number'] = 1;
            $data['highest_number'] = 0;
        }
        $data['total_sales'] = $goods['total_sales'];
        $data['is_virtual_sales'] = $goods['is_virtual_sales'];
        $data['virtual_sales'] = $goods['virtual_sales'];
        $data['totalStock'] = $goods['totalStock']; //总库存
        $data['play_info'] = $goods['tourists'];   //是否需要游客信息
        $data['visitor_info'] = $goods['tourists'] ? $goods['touristsInfo'] : ''; //所需游客填写的信息
        $data['ticket_changing_status'] = $goods['ticket_changing'];
        $data['ticket_changing_audit'] = $goods['ticket_changing_audit'];
        $data['putawayStartTimeing'] = $goods['putawayStartTimeing'];
        $data['putawayEndTimeing'] = $goods['putawayEndTimeing'];
        $data['tags'] = $goods['tags'];
        $data['store_id'] = $goods['store_id'];
        $data['scenic_id'] = $goods['scenic_id'];
        $data['goods_name'] = $goods['goods_name'];
        $data['title'] = $goods['title'];
        $data['details'] = $goods['details'];
        $data['category_id'] = $goods['category_id'];
        $data['is_notes'] = $goods['is_notes'];
        $data['is_id_number'] = $goods['is_id_number'];
        $data['id_card_rule'] = $goods['id_card_rule'];
        $data['assembling_place'] = $goods['assembling_place'];
        $data['destination'] = $goods['destination'];
        $data['subtract'] = $goods['subtract'];
        $data['coupons'] = MarketingCoupons::getUsersProductIdsReceiveCoupons($goods['scenic_id'], $goods['id']);
        return $data;
    }


    //验证规则
    // protected function getCheckRulesText()
    // {
    //     $goods = self::$_goods;
    //     $validation_rules = $goods['checkRules'] ? '整批':'分批';
    //     $str = $goods['checkNumber'] ? $validation_rules.'验证,最少验证'.$goods['checkNumber'].'张' : $validation_rules.'验证不限制';
    //     return $str;
    // }


    /**
     * [getStore 供应商信息]
     * @Author   ZhouYunpeng
     * @DateTime 2021-06-10
     * @return   [type]      [description]
     */
    public function getStore()
    {
        $goods = self::$_goods;
        $store = new Store();
        $row = $store->field('id,store_name,phone,avatar')->where('id', $goods['store_id'])->find();
        return $row;
    }


    /**
     * [getRefundRulesText 退款设置]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    private function getRefundRulesText()
    {
        $goods = self::$_goods;
        if (isset($goods['re_regulations']) && $goods['re_regulations']) {
            $refund = $goods['re_regulations'];
        } else {
            if ($goods['refundRules'] == 0) {
                $refund = '下单后不支持退款';
            } else {
                if ($goods['refundRules'] == 1) {
                    $refund = '有效期前未消费随时可退款';
                } elseif ($goods['refundRules'] == 2) {
                    $refund = '';
                    //有效期内
                    if ($goods['refundTimeBar'] == 1) {
                        if ($goods['refundTimeBarDay']) {
                            $beforeTime = '①有效期前' . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '前';
                            $afterTime = "\r\n②有效期前" . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '后';
                        } else {
                            $beforeTime = '①使用日期当天' . date('H:i', $goods['refundTimeBarTime']) . '前申请';
                            $afterTime = "\r\n②使用日期当天" . date('H:i', $goods['refundTimeBarTime']) . '后申请';
                        }

                        //有效期前
                        if ($goods['refundChargePlan'] == 0) {
                            $refund .= $beforeTime . '退款,无手续费';
                        } elseif ($goods['refundChargePlan'] == 1) {
                            $refund .= $beforeTime . '退款,扣手续费￥' . $goods['refundChargeMoney'] . '元/笔';
                        } else {
                            $refund .= $beforeTime . '退款,扣手续费￥' . $goods['refundChargeMoney'] . '元/张';
                        }
                        // 有效期前后
                        if ($goods['refundChargePlanAfter'] == 0) {
                            $refund .= $beforeTime . '退款,无手续费';
                        } elseif ($goods['refundChargePlanAfter'] == 1) {
                            $refund .= $afterTime . '退款,扣手续费￥' . $goods['refundChargeMoneyAfter'] . '元/笔';
                        } else {
                            $refund .= $afterTime . '退款,扣手续费￥' . $goods['refundChargeMoneyAfter'] . '元/张';
                        }
                    } else {
                        $beforeTime = '①有效期后' . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '内';
                        if ($goods['refundChargePlan'] == 0) {
                            $refund .= '过有效期后,无手续费';
                        } elseif ($goods['refundChargePlan'] == 1) {
                            $refund .= $beforeTime . '退款扣手续费￥' . $goods['refundChargeMoney'] . '元/笔';
                        } else {
                            $refund .= $beforeTime . '退款扣手续费￥' . $goods['refundChargeMoney'] . '元/张';
                        }
                    }
                }

            }
        }
        if (!$goods['refundRules']) {
            $value[] = ['title' => '退款规则:', 'value' => '不可退'];
        } else {
            $refundRules = $goods['refundRules'] == 1 ? '随时退' : '有条件退款';
            $value[] = ['title' => '退款规则:', 'value' => $refundRules];
            $value[] = ['title' => '退款费用:', 'value' => $refund];
        }

        return $value;
    }


    /**
     * [getRefundRulesText 退款设置]
     * @Author   ZhouYunpeng
     * @DateTime 2022-03-26
     * @return   [type]      [description]
     */
    public function getRefundRulesText2($id)
    {
        $goods = $this->where(['id' => $id])->find();
        if (isset($goods['re_regulations']) && $goods['re_regulations']) {
            $refund = $goods['re_regulations'];
        } else {
            if ($goods['refundRules'] == 0) {
                $refund = '下单后不支持退款';
            } else {
                if ($goods['refundRules'] == 1) {
                    $refund = '有效期前未消费随时可退款';
                } elseif ($goods['refundRules'] == 2) {
                    $refund = '';
                    //有效期内
                    if ($goods['refundTimeBar'] == 1) {
                        if ($goods['refundTimeBarDay']) {
                            $beforeTime = '①有效期前' . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '前';
                            $afterTime = "\r\n②有效期前" . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '后';
                        } else {
                            $beforeTime = '①使用日期当天' . date('H:i', $goods['refundTimeBarTime']) . '前申请';
                            $afterTime = "\r\n②使用日期当天" . date('H:i', $goods['refundTimeBarTime']) . '后申请';
                        }

                        //有效期前
                        if ($goods['refundChargePlan'] == 0) {
                            $refund .= $beforeTime . '退款,无手续费';
                        } elseif ($goods['refundChargePlan'] == 1) {
                            $refund .= $beforeTime . '退款,扣手续费￥' . $goods['refundChargeMoney'] . '元/笔';
                        } else {
                            $refund .= $beforeTime . '退款,扣手续费￥' . $goods['refundChargeMoney'] . '元/张';
                        }
                        // 有效期前后
                        if ($goods['refundChargePlanAfter'] == 0) {
                            $refund .= $beforeTime . '退款,无手续费';
                        } elseif ($goods['refundChargePlanAfter'] == 1) {
                            $refund .= $afterTime . '退款,扣手续费￥' . $goods['refundChargeMoneyAfter'] . '元/笔';
                        } else {
                            $refund .= $afterTime . '退款,扣手续费￥' . $goods['refundChargeMoneyAfter'] . '元/张';
                        }
                    } else {
                        $beforeTime = '①有效期后' . $goods['refundTimeBarDay'] . '天' . date('H:i', $goods['refundTimeBarTime']) . '内';
                        if ($goods['refundChargePlan'] == 0) {
                            $refund .= '过有效期后,无手续费';
                        } elseif ($goods['refundChargePlan'] == 1) {
                            $refund .= $beforeTime . '退款扣手续费￥' . $goods['refundChargeMoney'] . '元/笔';
                        } else {
                            $refund .= $beforeTime . '退款扣手续费￥' . $goods['refundChargeMoney'] . '元/张';
                        }
                    }
                }

            }
        }
        if (!$goods['refundRules']) {
            $value[] = ['title' => '退款规则:', 'value' => '不可退'];
        } else {
            $refundRules = $goods['refundRules'] == 1 ? '随时退' : '有条件退款';
            $value[] = ['title' => '退款规则:', 'value' => $refundRules];
            $value[] = ['title' => '退款费用:', 'value' => $refund];
        }

        return $value;
    }

    /**
     * [getDeadlineTypeText 验证有效期]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    public function getDeadlineTypeText()
    {
        $goods = self::$_goods;
        if ($goods['deadlineType'] == self::DEADLINETYPE_1) {
            if ($goods['deadlineFront'] && $goods['deadlineLater']) {
                $indate = '当日及前' . $goods['deadlineFront'] . '天有效' . '及后' . $goods['deadlineLater'] . '天有效';
            } elseif ($goods['deadlineFront']) {
                $indate = '当日及前' . $goods['deadlineFront'] . '天有效';
            } elseif ($goods['deadlineLater']) {
                $indate = '当日及后' . $goods['deadlineLater'] . '天有效';
            } else {
                $indate = '当日有效';
            }
        } elseif ($goods['deadlineType'] == self::DEADLINETYPE_2) {
            $valid_period_start = $goods['advance_booking'] ? '开业' : datetime($goods['valid_period_start'], 'Y-m-d');
            $valid_period_end = datetime($goods['valid_period_end'], 'Y-m-d');
            $week_list = $this->getWeekList();
            $valid_week = $this->getValidPeriodWeekTextAttr('', $goods);
            $indate = $valid_period_start . '至' . $valid_period_end . '选一天使用' . ($valid_week ? '<br/>可用时间：' . $valid_week : '');
        } else {
            $indate = '当日有效';
        }

        if ($goods['ch_regulations']) {
            $indate = $indate . '【' . $goods['ch_regulations'] . '】';
        }
        return $indate;
    }


    /**
     * [getParkWaysText 入园方式]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    private function getParkWaysText()
    {
        $goods = self::$_goods;
        $valueArr = $valueArr = explode(',', $goods['parkProve']);
        $list = $this->getParkproveList();

        if ($goods['other_way']) {
            //选择其他凭证
            $value = '凭' . $goods['other_way'] . '及' . implode('、', array_intersect_key($list, array_flip($valueArr)));
        } else {
            $value = '凭' . implode('、', array_intersect_key($list, array_flip($valueArr)));
        }

        $value .= $goods['parkWays'] == 0 ? '直接验证入园' : '换票入园';
        return $value;
    }

    /**
     * [getBeforeDay description]
     * @Author   ZhouYunpeng
     * @DateTime 2021-09-11
     * @return   [type]      [description]
     */
    private function getBeforeDay()
    {
        $goods = self::$_goods;
        if ($goods['advance_booking']) {
            $value = '预售票';
        } else {
            $value = '预定说明';
            // if ($goods['before'] == 0) {
            //     $value = '可订今日';
            // } elseif ($goods['before'] == 1) {
            //     $value = '可订今日';
            // } elseif ($goods['before'] == 2) {
            //     $value = '可订明日';
            // }
        }

        return $value;
    }

    /**
     * [getBeforeText 提前购买设置]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    private function getBeforeText()
    {
        $goods = self::$_goods;
        if (isset($goods['regulations']) && $goods['regulations']) {
            $value = $goods['regulations'];
        } else {
            if ($goods['deadlineType'] == 2 && $goods['valid_period_start'] > time()) {
                $value = '限时抢购';
            } else {
                if ($goods['before'] == 0) {
                    $value = '随买随用';
                } elseif ($goods['before'] == 1) {
                    $value = '用户需出行前' . $goods['beforeHour'] . '小时' . $goods['beforeMinute'] . '分钟购买';
                } elseif ($goods['before'] == 2) {
                    if ($goods['beforeDay'] == 0) {
                        $value = '用户需出行当日' . date("H:i", $goods['beforeTime']) . '前下单';
                    } else {
                        $value = '用户需出行前' . $goods['beforeDay'] . '天的' . date("H:i", $goods['beforeTime']) . '前下单';
                    }

                }

            }
        }

        return $value;
    }


    /**
     * [getValidPeriod 商品自定义有效]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    public function getValidPeriod()
    {
        $goods = self::$_goods; //商品数据
        if ($goods['deadlineType'] != self::DEADLINETYPE_2) {
            return;
        }
        $data = [];
        $data['valid_period_info'] = $this->getDeadlineTypeText();
        $data['valid_period_expire'] = $this->validity_period() ? 1 : 0;//有效期是否结束
        return $data;
    }


    /**
     * [getParkproveList 入园方式]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @return   [type]      [description]
     */
    public function getParkproveList()
    {
        return ['qr' => '二维码', 'g' => '团券码', 'ids' => '身份证', 'p' => '手机号'];
    }


    /**
     * [refundRule 退款规则：有条件退款时间限制]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $goods_id  [description]
     * @param    [type]      $play_time [description]
     * @return   [type]                 [description]
     */
    public function refundRule($goods_id, $play_time)
    {
        $where = [
            'id' => $goods_id,
            'refundRules' => 2, //有条件退款
        ];
        $goods = $this->where($where)->find();
        //验证有效期结束日期
        if ($goods['deadlineType'] == self::DEADLINETYPE_0 || $goods['deadlineType'] == self::DEADLINETYPE_1) {
            //当日有效或当日及前后x天有效
            if ($goods['deadlineType'] == self::DEADLINETYPE_0 || $goods['deadlineFront']) {
                //有效期:当日有效或前x天有效
                $valid = $play_time;
            } elseif ($goods['deadlineLater']) {
                //有效期：当日及后x天有效
                $valid = strtotime("+ $goods->deadlineLater day", $play_time); //游玩时间后x天
            }
        } elseif ($goods['deadlineType'] == self::DEADLINETYPE_2) {
            //自定义有效期
            $valid = $goods['valid_period_end'];//结束时间
        }


        //退款规则
        $package = function ($goods, $valid) {
            $salesModel = new Sales();
            $sales = $salesModel->get(['goods_id' => $goods['id']]);
            //有效期内
            if ($goods['refundTimeBar'] == 1) {
                // $refund_time = $this->join_time($valid, $goods['check_end_time']);
                // $refund_time = strtotime("- $goods->refundTimeBarDay day", $valid);
                // $refund_time = $this->join_time($refund_time, $goods['refundTimeBarTime']);
                $refund_time = strtotime("+1 day");
            } elseif ($goods['refundTimeBar'] == 2) {
                //有效期后
                $refund_time = strtotime("+ $goods->refundTimeBarDay day", $valid);
                $refund_time = $this->join_time($refund_time, $goods['refundTimeBarTime']);
            }

            return $refund_time;
        };
        //退款有限期
        if ($goods['refundTimeBar'] == 1) {
            //有效期前X天内可退
            $indate = $package($goods, $valid);
            if (time() <= $indate) {
                return true;
            }
        } elseif ($goods['refundTimeBar'] == 2) {
            //可退时间 有效期后X天内可退
            $front_time = $package($goods, $valid);
            if ($front_time >= time()) {
                return true;
            }
        }
        return false;
    }

    /**
     * [validity_period 有效期:自定义有效期]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param integer $goods_id [description]
     * @return   [type]                [description]
     */
    public function validity_period($goods_id = 0)
    {
        if ($goods_id) {
            $goods = $this->get(['id' => $goods_id]);
        } else {
            $goods = self::$_goods;
        }
        if ($goods['deadlineType'] == self::DEADLINETYPE_2 && strtotime("today") > $goods['valid_period_end']) {

            //自定有效期,当前时间大于有效期结束时间，停止售票
            return false;
        }

        return true;
    }

    /**
     * [expire 订单过期]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $goods_id  [description]
     * @param    [type]      $play_time [description]
     * @return   [type]                 [description]
     */
    public function expire($goods_id, $play_time)
    {
        $goods = $this->get(['id' => $goods_id]);
        if ($goods['deadlineType'] == self::DEADLINETYPE_1) {
            if ($goods['deadlineLater']) {
                //当日后几天有效，订单过期日期为游玩日期往后推迟几天
                $later_day = $goods['deadlineLater'];
                $expire_time = strtotime("+ $later_day day", $play_time);
            } else {
                //当日及前后天数都为0或前x天存在，过期日期默认为游玩日期结束后
                $expire_time = $play_time;
            }
        } elseif ($goods['deadlineType'] == self::DEADLINETYPE_2) {
            //自定义有效期：订单过期日期为该自定义日期的结束日期
            $expire_time = $goods['valid_period_end'];
        } else {
            //当日有效：过期时间为游玩日期当天
            $expire_time = $play_time;
        }
        $expire_time = strtotime("23:59", $expire_time);
        if (\time() > $expire_time) {
            return true;
        }
        return false;
    }


    /**
     * [join_time 更改日期]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $timestamp [description]
     * @param    [type]      $time      [description]
     * @return   [type]                 [description]
     */
    public function join_time($timestamp, $time)
    {
        $time = date('H:i', $time);
        return strtotime($time, $timestamp);
    }

    /**
     * [expired_operation 过期规则操作]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $goods_id [description]
     * @param    [type]      $order_id [description]
     * @return   [type]                [description]
     */
    public function expired_operation($goods_id, $order_id)
    {
        $where = [
            'order_id' => $order_id,
            'status' => OrderGoods::STATUS_EXPIRE
        ];
        $goods = $this->get(['id' => $goods_id]);
        $expires_num = OrderGoods::where($where)->count();

        Db::startTrans();
        try {
            if ($goods['over'] == self::EXPIRED_1) {
                //自动完结,仅与分销商结算费用，不予供应商结算费用。
                Rebate::executeDistributorRebate($order_id, $expires_num);
            } elseif ($goods['over'] == self::EXPIRED_2) {
                //自动验证,与分销商及供应商结算费用   
                Rebate::executeRebate($order_id, $expires_num); //返利
            }/* else {
               Rebate::deleteRebate($order_id);//不予任何人结算
            }*/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
    }


    /**
     * [reserve 提前购买限制]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $goods_id [description]
     * @param    [type]      $date     [description]
     * @return   [type]                [description]
     */
    public function reserve($goods, $date)
    {

        if ($goods['before'] == 1) {
            //提前小时、分钟
            $minute = $goods['beforeHour'] * 60;//小时转分钟
            $minute = $minute + $goods['beforeMinute'];
            if (!$minute) {
                //不能为0
                return true;
            }
            $check_end = $this->join_time($date, $goods['check_end_time']);//转换当前时间
            $end_time = strtotime("-$minute Minute", $check_end);
            //超过该时间，禁止销售
            return $this->timeSize($end_time);
        } elseif ($goods['before'] == 2) {
            //用户需在游玩x天x时x分前购
            list($start, $end) = Time::today();
            $play_date = $date;//游玩日期
            //天数为0时，默认当前日期
            $buy_date = $start;
            if ($goods['beforeDay']) {
                $buy_date = strtotime("+" . $goods["beforeDay"] . "day", $start);
            }
            //游玩日期小于商品设置的购买日期，禁止销售
            if ($play_date <= $buy_date) {
                if ($play_date === $buy_date) {
                    // $before_time = $this->join_time($date,$goods['beforeTime']);
                    // return $this->timeSize($before_time);
                    if (date('H:i', $goods['beforeTime']) > date('H:i', time())) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }
        }
        return true;
    }

    /**
     * [timeSize 与当前时，分对比]
     * @Author   ZhouYunpeng
     * @DateTime 2021-04-17
     * @param    [type]      $time [description]
     * @return   [type]            [description]
     */
    private function timeSize($time)
    {
        if (!$time) {
            return true;
        }
        if ($time - \time() > 0) {
            return true;
        }
        return false;
    }


    /**
     * [tag 商品标签]
     * @Author   ZhouYunpeng
     * @DateTime 2021-01-15
     * @param    [type]      $ids  [description]
     * @param boolean $type [description]
     * @return   [type]            [description]
     */
    public function tag($ids, $type = true)
    {
        $where = ['goods_status' => 1];
        if ($type) {
            //商品id
            $where['id'] = $ids;
            $goods = self::$_goods ? self::$_goods : $this->where($where)->find();
            if (array_key_exists('is_custom', $goods) && $goods['is_custom']) {
                return explode(',', $goods['tags']);
            }

            $before = $goods['before'] == 1 ? $this->getBeforeStatusAttr(2) : $this->getBeforeStatusAttr($goods['before']);
            $list = [$before, $this->getRefundStatusAttr($goods['refundRules'])];
        } else {
            //景区
            $where['scenic_id'] = $ids;
            $list = self::where($where)->field('before,refundRules')->select();
            if ($list) {
                $list = collection($list)->toArray();
                $tag = reset($list);
                $list = [$this->getBeforeStatusAttr($tag['before']), $this->getRefundStatusAttr($tag['refundRules'])];
                foreach ($list as &$tag) {
                    if ($tag === '可订明日') {
                        $tag = '需提前购买';
                    }
                }
            }
        }

        if (in_array('不可退款', $list)) {
            unset($list[1]);
        }
        return $list;
    }


    /**
     * [getDetails 商品详情]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-24
     * @param    [type]      $scenic_id [description]
     * @param    [type]      $goods_id  [description]
     * @return   [type]                 [description]
     */
    public function getDetails($scenic_id, $goods_id)
    {

        $scenicModel = new Scenic();
        //景区信息
        $scenic = $scenicModel->getScenic($scenic_id);
        $scenic['minPrice'] = $scenicModel->getMinPrice($goods_id);
        $data['scenic'] = $scenic;
        $data['goods'] = $this->goodsInfo($goods_id);
        $data['goods']['retailPrice'] = Sales::retail_price(['id' => $goods_id, 'sales_status' => 1]);
        if ($data['goods']['category_id'] > 1) {
            $storeModel = new Store();
            $data['store'] = $storeModel->field('avatar image,store_name,mobile phone')->find($data['goods']['store_id']);
            $data['image'] = $scenic['scenic_images'];
            $data['avg_mark'] = $scenic['score'];
            $salesModel = new Sales();
            $sales = $salesModel->get(['goods_id' => $goods_id]);
            $data['goods']['minPrice'] = $sales['salePrice'];
        }
        return $data;
    }


}
